package com.demo.tableversion.config;

import com.demo.tableversion.controller.Message;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@ControllerAdvice
@Component
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
    public Message onException(SQLIntegrityConstraintViolationException e){
        e.printStackTrace();
        String message = e.getMessage();
        Pattern compile = Pattern.compile(".*('.*?').*('.*?')");
        Matcher matcher = compile.matcher(message);
        if(matcher.matches()){
            String group = matcher.group(1);
            String group1 = matcher.group(2);
            return Message.on().ofMessage(String.format("字段唯一性冲突: %s.%s",group,group1))
                    .ofState(400)
                    .ofResult(null);
        }
        return Message.onFailed().ofMessage(message);
    }

}
